<template>
  <view class="tw-bluetooth-tool">
    <view class="header">
      <view class="header-title">当前操作设备</view>
      <view class="header-button">
        <!-- size="medium" -->
        <wd-button
          size="small"
          plain
          :round="false"
          block
          @click="onSearchDevice"
          icon="search1"
          v-if="!isScan"
          >搜索设备</wd-button
        >
        <wd-button size="small" plain :round="false" block loading v-else>搜索中</wd-button>
      </view>
    </view>
    <view class="content">
      <scroll-view class="device-list" scroll-y v-if="deviceList.length">
        <view
          class="bluetooth-card"
          v-for="item in deviceList"
          :key="item.deviceId"
          :class="{ active: item.isConnect }"
        >
          <view class="bluetooth-card-left">
            <view class="equipment-name">
              设备名称：{{ item.name || '未知' }}
              <text :class="{ status: item.isConnect }"></text>
            </view>
            <view class="equipment-id">设备ID：{{ item.deviceId || '未知' }}</view>
          </view>
          <view class="bluetooth-card-right">
            <view class="button">
              <wd-button
                type="error"
                size="small"
                plain
                @click="onDisconnectDevice(item)"
                icon="link-unlink"
                v-if="item.isConnect"
                >断开</wd-button
              >
              <wd-button
                size="small"
                @click="onConnectDevice(item)"
                classPrefix="icon"
                icon="bluetooth"
                v-else
                >连接</wd-button
              >
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="no-connect" v-else>暂无设备</view>
      <!-- v-if="deviceStore.curDevice.deviceId" -->
      <!-- <bluetooth-card :deviceData="deviceStore.curDevice"></bluetooth-card> -->
      <!-- <wd-transition :show="deviceListShow" name="fade"> -->
      <!-- <scroll-view class="device-list" scroll-y>
        <view class="device-list-item" v-for="item in deviceList" :key="item.deviceId">
          <bluetooth-card :deviceData="item"></bluetooth-card>
        </view>
      </scroll-view> -->
      <!-- </wd-transition> -->
    </view>
  </view>
</template>

<script setup>
defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})
// import bluetoothCard from './bluetooth-card.vue'
// import bluetoothTool, { bluetooth } from '@/utils/bluetooth'
import { pause } from 'wot-design-uni/components/common/util'
import { computed, ref } from 'vue'
import bluetoothTool from '@/utils/bluetooth'
import { useDeviceStore, useGlobalStore } from '@/stores/'
const deviceStore = useDeviceStore()
const globalStore = useGlobalStore()
// 设备列表
const deviceList = computed(() => {
  return deviceStore.deviceList.map((item) => {
    item.isConnect = globalStore.connDeviceList.includes(item.deviceId)
    return item
  })
})
// 搜索状态
const isScan = ref(false)
// 搜索设备
async function onSearchDevice() {
  isScan.value = true
  try {
    const res = await bluetoothTool.scanBlueTooth()
    console.log('res:', res)
    // await onConnectDevice(res[0])
  } finally {
    isScan.value = false
  }
}
// 连接设备
async function onConnectDevice(device) {
  await onDisconnectDevice(deviceStore.curDevice)
  await bluetoothTool.connectDevice(device)
  // 设置最大传输单元127
  // await pause(500)
  // await bluetoothTool.setBLEMTU(device.deviceId, 127)
  await pause(500)
  initTork()
}

// 断开连接
async function onDisconnectDevice(device) {
  await bluetoothTool.disconnectDevice(device)
  console.log('断开连接')
}

// 初始化Tork 获取设备临界值 设置心跳帧数
async function initTork() {
  // return new Promise((resolve, reject) => {
  const opts = deviceStore.getOpts()
  console.log('opts:', opts)
  // 下发读取设备临界值
  const cmd = getApp().globalData.protosUtils.cmd.getCmd('critical')
  await bluetoothTool.sendToDevice(opts.write, cmd, () => {
    // 监听变化
    uni.$once(uni.$myNotifyEventName, (data) => {
      const readRes = getApp().globalData.protosUtils.readDeviceCriticalValue(data)
      console.log('readRes:', readRes)
      deviceStore.setCurDeviceItem('criticalData', readRes)
    })
  })

  await pause(500)
  // 设置心跳帧数 间隔
  const cmd2 = getApp().globalData.protosUtils.cmd.setCmd('heartbeat')
  await bluetoothTool.sendToDevice(opts.write, cmd2)
}
</script>

<style lang="scss" scoped>
.tw-bluetooth-tool {
  padding: 10px;
  background: $my-background-color-1;
  border-radius: $my-border-radius-m;
  .header {
    @include flex-box();
    // padding-bottom: 6px;
    // border-bottom: 1px solid $my-border-color-dark;
    &-title {
      font-weight: 700;
    }
    &-button {
      transform: scale(1.1);
    }
  }
  .content {
    .device-list {
      max-height: 200px;
    }
    .bluetooth-card {
      @include flex-box();
      margin-top: 6px;
      padding-top: 6px;
      border-top: $common-border-dark;
      transition: all 0.3s;
      &.active {
        font-weight: 700;
      }
      &-left {
        font-size: $my-text-font-size-base;
        .equipment-name {
          .status {
            // font-size: ;
            // font-weight: 700;
            display: inline-block;
            width: 11px;
            height: 11px;
            margin-left: 4px;
            background: $my-color-green;
            border-radius: 50%;
            // &.disconnect {
            //   background: $my-color-red;
            // }
          }
        }
        .equipment-id {
          margin-top: 4px;
        }
      }
    }
    .no-connect {
      @include flex-box-set(center);
      height: 36px;
    }
  }
}
</style>
